How to query an xml document using XQuery via BaseX.
BaseX is a powerful XML database and XQuery processor that allows you to store, query, and manipulate XML data efficiently. Here’s a step-by-step guide to querying an XML document using XQuery in BaseX.
LibraryDB
).library.xml
).Here’s a sample XML document you might use:
<library>
<book id="1">
<title>Learning XQuery</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book id="2">
<title>Advanced XQuery</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
</library>
Here are some common queries you can run against the XML document.
1. Retrieve All Book Titles
for $book in /library/book
return $book/title
2. Filter Books by Price
To find books with a price greater than 30:
for $book in /library/book
where $book/price > 30
return <result>
<title>{$book/title/text()}</title>
<author>{$book/author/text()}</author>
</result>
3. Sort Books by Title
To sort books alphabetically by title:
for $book in /library/book
order by $book/title
return <result>
<title>{$book/title/text()}</title>
<author>{$book/author/text()}</author>
</result>
4. Generate a New XML Structure
Create a new XML catalog:
<catalog>
{
for $book in /library/book
return <item>
<title>{$book/title/text()}</title>
<author>{$book/author/text()}</author>
<price>{$book/price/text()}</price>
</item>
}
</catalog>
Ctrl + Enter
).You can view the results in various formats, including XML, text, or JSON, depending on your needs.
Using XQuery in BaseX allows you to efficiently query and manipulate XML data. With its powerful querying capabilities, BaseX is an excellent tool for working with XML documents. If you have further questions or need specific examples, feel free to ask!